import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Spin, Button, Input } from 'antd';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import router from 'umi/router';
import AdSelect from '@/components/AdSelect';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AdButton from '@/components/AdButton';
import prompt from '@/components/Prompt';
import { formItemFragement, queryDict, formatPrice } from '@/utils/common';
import { checkStrLength } from '@/pages/Common/common';
import { allDictList } from '@/utils/constans';
import {
  selectCabinetOilList,
  selectCabinetOilDetailAndInfo,
  routeUrl,
  codes,
  allDispatchType,
  EmptyList,
} from './utils';

const { TextArea } = Input;

@connect(({ cabinetOil, component, loading, common }) => ({
  cabinetOilDetail: cabinetOil.cabinetOilDetail,
  dictObject: component.dictObject,
  formValues: cabinetOil.formValues,
  loading: loading.effects[allDispatchType.detail],
}))
@Form.create()
export default class CabinetOilOperate extends Component {
  state = {
    detailId: '',
    disabled: false,
    isEmpty: 'true',
    weightEnd: '',
    weightStart: '',
  };

  componentWillMount() {
    const allDict = [allDictList.cabinetType, allDictList.oilWearType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      cabinetOilDetail,
    } = this.props;
    this.handleStateChange([{ detailId: id }]);
    const detail = cabinetOilDetail[id];
    // if (detail) return;
    this.getCabinetOilDetails(id);
  }
  getCabinetOilDetails = id => {
    const {
      match: { params },
    } = this.props;
    const cabinetOilId = id || params.id;
    cabinetOilId &&
      selectCabinetOilDetailAndInfo({
        type: allDispatchType.detail,
        payload: { id: cabinetOilId },
        props: this.props,
        callback: data => {
          this.setState(pre => ({
            isEmpty: data.beEmpty,
            weightEnd: data.weightEnd,
            weightStart: data.weightStart,
            // disabled:!pre.disabled
          }));
        },
      });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  setTabName = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setTabsName',
      payload,
      callback: data => {
        if (!data) return;
        router.push(`${routeUrl.edit}/${payload.id}`);
      },
    });
  };

  /**
   * 操作数据
   */
  saveInfo = () => {
    const {
      form,
      dispatch,
      cabinetOilDetail,
      match: {
        params: { id },
      },
    } = this.props;
    const { } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const { ...params } = values;
      if (id) {
        params.id = id;
      }
      this.dispatchOperate(params);
    });
  };

  dispatchOperate = params => {
    const { dispatch, formValues } = this.props;
    dispatch({
      type: allDispatchType.operate,
      payload: params,
      callback: data => {
        if (!data) return;
        const id = params.id;
        this.setState(preState => ({
          disabled: !preState.disabled,
        }));

        if (id) {
          this.getCabinetOilDetails(id);
        } else {
          this.setTabName({
            id: data,
            isReplaceTab: true,
          });
        }
        selectCabinetOilList({ payload: formValues, props: this.props });
      },
    });
  };

  headerOperate = () => {
    const {
      match: {
        params: { id },
      },
      cabinetOilDetail,
    } = this.props;
    const { disabled, detailId } = this.state;
    const detail = cabinetOilDetail[detailId] || {};
    return (
      <div>
        {!disabled ? (
          <>
            <Button.Group>
              <AdButton
                text="保存"
                type="primary"
                code={codes.add}
                onClick={() => this.saveInfo()}
              />
              {id && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                  code={id ? codes.edit : codes.add}
                />
              )}
            </Button.Group>
          </>
        ) : (
            <Button.Group>
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="编辑"
                type="primary"
                code={id ? codes.edit : codes.add}
              />
            </Button.Group>
          )}
      </div>
    );
  };

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  inputOnBlur = (val, type) => {
    const { weightEnd, weightStart } = this.state;
    const {
      form: { getFieldsValue, setFieldsValue },
    } = this.props;
    if (weightEnd && weightStart && Number(weightEnd) < Number(weightStart)) {
      const content = type == 'weightStart' ? '最小值不能大于最大值' : '最大值不能小于最小值';
      prompt({ content, type: 'warn' });
      setFieldsValue({ [type]: '' });
      this.setState({
        [type]: '',
      });
    }
  };

  changeVal = (val, type) => {
    this.setState({
      [type]: val,
    });
  };

  render() {
    const { detailId, disabled, isEmpty, weightEnd, weightStart } = this.state;

    const { form, cabinetOilDetail, loading, dictObject } = this.props;
    const getFieldDecorator = form.getFieldDecorator;
    const detail = cabinetOilDetail[detailId] || {};

    const editPageParams = {
      title: `${detailId ? '编辑' : ' 新增'}柜型标准油耗`,
      headerOperate: this.headerOperate(),
      panelValue: [{ key: '基础信息' }],
    };
    const commonParams = {
      getFieldDecorator,
    };

    const formItem = [
      [
        <AntdFormItem
          label="是否放空"
          code="beEmpty"
          initialValue={isEmpty}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AdSelect
            isExist={true}
            data={EmptyList}
            disabled={disabled}
            onChange={val => {
              this.setState({
                isEmpty: val,
              });
            }}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="柜型"
          rules={[{ required: true }]}
          code="cabinetType"
          initialValue={detail.cabinetType}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            isExist={true}
            data={dictObject[allDictList.cabinetType]}
            payload={{ code: allDictList.cabinetType }}
          />
        </AntdFormItem>,
      ],

      isEmpty == 'false' && [
        <AntdFormItem
          label="重量(大于等于)"
          code="weightStart"
          rules={[{ required: true }]}
          initialValue={formatPrice(weightStart)}
          {...commonParams}
        >
          <AntdInput
            disabled={disabled}
            mode="anyNumber"
            onChange={val => this.changeVal(val, 'weightStart')}
            onBlur={e => this.inputOnBlur(e, 'weightStart')}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="重量(小于)"
          code="weightEnd"
          rules={[{ required: true }]}
          initialValue={formatPrice(weightEnd)}
          {...commonParams}
        >
          <AntdInput
            disabled={disabled}
            mode="anyNumber"
            onChange={val => this.changeVal(val, 'weightEnd')}
            onBlur={e => this.inputOnBlur(e, 'weightEnd')}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="标准油耗"
          code="standardOilWear"
          rules={[{ required: true }]}
          initialValue={formatPrice(detail.standardOilWear)}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="油耗标准类型"
          code="oilWearType"
          rules={[{ required: true }]}
          initialValue={detail ? detail.oilWearType : ''}
          {...commonParams}
        >
          <AdSelect
            data={dictObject[allDictList.oilWearType]}
            payload={{ code: allDictList.oilWearType }}
            disabled={disabled}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remarks"
          rules={[
            {
              validator: (rule, value, callback) => {
                checkStrLength(rule, value, callback, 200, '备注');
              },
            },
          ]}
          initialValue={detail.remarks}
          {...commonParams}
        >
          <TextArea disabled={disabled} rows={4} />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={detailId ? loading : false}>
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
        </Spin>
      </EditPage>
    );
  }
}
